package cn.jiahua.hospital.controller;

import cn.jiahua.hospital.constants.Constants;
import cn.jiahua.hospital.constants.ResultEnum;
import cn.jiahua.hospital.dto.*;
import cn.jiahua.hospital.pojo.*;
import cn.jiahua.hospital.service.*;
import cn.jiahua.hospital.service.impl.ScheduleServiceImpl;
import cn.jiahua.hospital.utils.RedisUtil;
import cn.jiahua.hospital.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.SchemaOutputResolver;
import java.util.*;

/**
 * @author guanliang
 * @Copyright公司名称 - Powered By 研发中心
 * @date 2021-04-24 14:41
 * @description:
 * @version:
 */
@Api(tags = "医生")
@RestController
@RequestMapping("/api/doctor/")
public class DoctorController {

    @Autowired
    DoctorService doctorService;
    @Autowired
    YOrderService yOrderService;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ReportService reportService;

    @Autowired
    ScheduleService scheduleService;

    @Autowired
    PayDoctorService payDoctorService;

    @Autowired
    DoctorRoleService doctorRoleService;


   /* //增字段dieseaseId 会报java: 不兼容的类型: java.lang.Integer无法转换为java.lang.String
    @ApiOperation(value = "添加医生接口", produces = "application/json", notes = "添加医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "identity", value = "身份证", required = true, dataType = "String"),
            @ApiImplicitParam(name = "nation", value = "民族", required = true, dataType = "String"),
            @ApiImplicitParam(name = "introduction", value = "简介", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pic", value = "照片", required = true, dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "手机号码", required = true, dataType = "String"),
            //@ApiImplicitParam(name="dieseaseId",value = "医生疾病id",required = true,dataType = "int" ),
            @ApiImplicitParam(name = "doctorGrage", value = "医生级别(1.专家/2.普通)", required = true, dataType = "int"),
            @ApiImplicitParam(name = "sex", value = "医生性别(1.男)", required = true, dataType = "int")
    })
    @PostMapping("add")
    public Object doctorAdd(String password, String account, String name, String identity, String nation,
                            String introduction, String pic,
                            String phone, Integer doctorGrage, int sex, MultipartFile file) {
        Doctor doctor = new Doctor(password, account, name, identity, nation, introduction, pic, phone, doctorGrage, sex);
        try {
            if (doctorService.qdtxAddDoctor(doctor) > 0)
                return ResultUtils.returnDataSuccess("back/doctor/add成功");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultUtils.returnFail("back/doctor/add失败", "30001");
        }
        return ResultUtils.returnFail("back/doctor/add失败", "30001");
    }*/


    @ApiOperation(value = "修改医生接口", produces = "application/json", notes = "修改医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId", value = "修改医生的id", required = true, dataType = "int"),
            /*@ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String"),*/
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "identity", value = "身份证", required = false, dataType = "String"),
            @ApiImplicitParam(name = "nation", value = "民族", required = false, dataType = "String"),
            @ApiImplicitParam(name = "introduction", value = "简介", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pic", value = "照片", required = false, dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "手机号码", required = false, dataType = "String"),
            @ApiImplicitParam(name = "dieseaseId", value = "医生疾病id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "doctorGrage", value = "医生级别(1.专家/2.普通)", required = false, dataType = "int"),
            @ApiImplicitParam(name = "sex", value = "医生性别(1.男)", required = false, dataType = "int")
    })
    @GetMapping("modify")
    public Result doctormodify(Integer doctorId, String name, String identity, String nation,
                               String introduction, String pic,
                               String phone, Integer dieseaseId, Integer doctorGrage, int sex) {
        /*  String token=request.getHeader("token");*/
//        String token="token:pc-1619492429678-b6fe4d-12345678910";
//        Doctor doctor= (Doctor) redisUtil.get(token);
//        System.out.println(token);

        Doctor doctor = new Doctor(doctorId, name, identity, nation, introduction, pic, phone, dieseaseId, doctorGrage, sex);
        Integer count = doctorService.qdtxModifyDoctor(doctor);
        if (count > 0) {
            return ResultUtils.returnDataSuccess("back/doctor/modify成功");
        }
        return ResultUtils.returnFail("back/doctor/modify", "30001");
    }


    @ApiOperation(value = "删除医生接口", produces = "application/json", notes = "删除医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "删除医生的id", required = true, dataType = "int"),
    })
    @PostMapping("delect")
    public Result doctorDelete(Integer id) {
        if (doctorService.qdtxDeleteDoctorById(id) > 0) {
            return ResultUtils.returnSuccess("back/doctor/delect成功", "30006");
        }
        return ResultUtils.returnFail("back/doctor/delect失败", "30001");

    }


    @ApiOperation(value = "拉黑医生接口", produces = "application/json", notes = "拉黑医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "医生的id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "state", value = "拉黑的状态", required = true, dataType = "int")
    })
    @PostMapping("forbidden")
    public Result doctorforbidden(Integer id, Integer state) throws DoctorExtion {
        if (doctorService.updateForbidden(id, state) > 0) {
            return ResultUtils.returnDataSuccess("back/doctor/forbidden成功");
        }
        return ResultUtils.returnFail("back/doctor/forbidden失败", "30001");
    }


    @ApiOperation(value = "查看医生得个人信息接口", produces = "application/json", notes = "查看医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "医生的id", required = true, dataType = "int"),
    })
    @PostMapping("selectId")
    public Result doctorselectId(Integer id) throws DoctorExtion {
        Doctor result = doctorService.getDoctorById(id);
        if (result == null) {
            return ResultUtils.returnFail("back/doctor/selectId", "30001");
        }
        return ResultUtils.returnDataSuccess(result);
    }


    @ApiOperation(value = "查看医生接口", produces = "application/json", notes = "查看医生所在得医院和科室疾病")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "医生的id", required = true, dataType = "int"),
    })
    @PostMapping("getDoctorView")
    public Result getDoctorView(Integer id) throws DoctorExtion {
        Doctor result = doctorService.getDoctorById(id);
        if (result == null) {
            return ResultUtils.returnFail("back/doctor/selectId", "30001");
        }
        return ResultUtils.returnDataSuccess(result);
    }


    @ApiOperation(value = "医生分页接口", produces = "application/json", notes = "分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "医生的姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "departmentsName", value = "科室名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "illnessName", value = "疾病名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", required = false, dataType = "String"),
            @ApiImplicitParam(name = "size", value = "页大小", required = false, dataType = "String")
    })
    @PostMapping("limit")
    public Result doctorLimit(String name, String departmentsName, String illnessName, Integer page, Integer size) throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        Doctor doctor = new Doctor();
        doctor.setName(name);
        doctor.setDepartmentsName(departmentsName);
        doctor.setIllnessName(illnessName);
        param.put("doctorlist", doctor);
        Page<Doctor> result = doctorService.getDoctorListlimit(param, page, size);
        if (result == null) {
            return ResultUtils.returnFail("back/doctor/selectId", "30001");
        }
        return ResultUtils.returnDataSuccess(result);
    }


    @ApiOperation(value = "修改医生个人信息接口", produces = "application/json", notes = "修改医生的个人信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId", value = "医生修改的ID", required = false, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "医生名字", required = false, dataType = "String"),
            @ApiImplicitParam(name = "introduction", value = "医生简介", required = false, dataType = "String"),
            @ApiImplicitParam(name = "file", value = "医生头像", required = false, dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "手机号码", required = false, dataType = "String")
    })
    @PostMapping("modifyMsg")
    public Result modifyMsg(Integer doctorId, String name, String introduction, String phone, String file) {
        /*  String token=request.getHeader("token");*/
        // Doctor doctor= (Doctor) redisUtil.get(token);

        Doctor doctor = new Doctor(doctorId, name, introduction, phone, file);
        try {
            if (doctorService.qdtxModifyDoctor(doctor) > 0) {
                return ResultUtils.returnDataSuccess("modfiyMsg成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail("修改信息失败", "30001");
        }
        return ResultUtils.returnFail();
    }


    @ApiOperation(value = "修改密码接口", produces = "application/json", notes = "医生修改密码的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "旧密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    @PostMapping("modifyPwd")
    public Result modifyPwd(String password, String newPassword, HttpServletRequest request) {
        /*  String token=request.getHeader("token");*/
        String token = "token:pc-1619492429678-b6fe4d-12345678910";
        Doctor doctor = (Doctor) redisUtil.get(token);
        if (doctor != null && doctor.getPassword().equals(password)) {
            System.out.println("密码正确");
            doctor.setPassword(newPassword);
            if (doctorService.qdtxModifyDoctor(doctor) > 0) {
                return ResultUtils.returnDataSuccess("成功");
            }
        }
        return ResultUtils.returnFail();
    }


    @ApiOperation(value = "取消预约接口", produces = "application/json", notes = "医生取消预约接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderid", value = "订单id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "订单状态1未支付，2已支付，3已完成，4已取消", required = true, dataType = "String")
    })
    @GetMapping("cancel")
    public Result cancel(Integer orderid, Integer status, HttpServletRequest request) {
        /*String token=request.getHeader("token");*/
        // String token="token:pc-1619492429678-b6fe4d-12345678910";
        //Doctor doctor= (Doctor) redisUtil.get(token);
        YOrder yOrder = yOrderService.getYOrderById(orderid);
        if (yOrder != null) {
            yOrder.setStatus(status);
            try {
                yOrderService.qdtxModifyYOrder(yOrder);
                return ResultUtils.returnDataSuccess("成功");
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtils.returnFail();
            }
        }
        return ResultUtils.returnFail();
    }


//
//    @ApiOperation(value = "生成报告接口", produces = "application/json", notes = "生成报告的接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "orderid", value = "订单的id", required = true, dataType = "int"),
//            @ApiImplicitParam(name = "reportName", value = "报告名称", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "content", value = "报告内容", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "creatTime", value = "创建时间", required = false, dataType = "String")
//    })
//    @PostMapping("setReport")
//    public Result setReport(Integer orderid, String reportName, String content, Date creatTime, HttpServletRequest request){
//        Report report=new Report(orderid,reportName,content,creatTime);
//        reportService.qdtxModifyReport(report);
//        return ResultUtils.returnFail();
//    }


    @ApiOperation(value = "生成报告接口", produces = "application/json", notes = "生成报告的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderid", value = "订单的id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "reportName", value = "报告名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "content", value = "报告内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "creatTime", value = "创建时间", required = false, dataType = "String")
    })
    @PostMapping("setReport")
    public Result setReport(Integer orderid, String reportName, String content, Date creatTime, HttpServletRequest request) {
        Report report = new Report(orderid, reportName, content, creatTime);
        reportService.qdtxModifyReport(report);
        return ResultUtils.returnFail();
    }


    @ApiOperation(value = "查看医生排班接口", produces = "application/json", notes = "查看医生本人的排班表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorid", value = "医生的id", required = true, dataType = "int"),
    })
    @GetMapping("getSchedule")
    public Result getSchedule(Integer doctorid, HttpServletRequest request) {
        Schedule schedule = new Schedule();
        schedule.setScheduleId(doctorid);
        scheduleService.getScheduleById(doctorid);
        return ResultUtils.returnFail();
    }

    @ApiOperation(value = "查看地区医院类型等级分页", produces = "application/json", notes = "根据地区、医院类型、医院等级查询医院")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorid", value = "医生的id", required = true, dataType = "int"),
    })
    @GetMapping("addressDoctor")
    public Result addressDoctor(String addressName, String hospitalTypeName, String hospitalgradeName) {

        return ResultUtils.returnFail();
    }


    @GetMapping("pageDoctor")
    @ApiImplicitParam(value = "医生id",name = "doctorId")
    @ApiOperation(value = "获取医生详情信息",notes = "获取医生页面的详情信息")
    public Result getDoctorPage(@RequestParam Integer doctorId){
        if (doctorId == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        List<PageDoctorDto> doctorPageInfo = null;
        try {
            doctorPageInfo = doctorService.getDoctorPageInfo(doctorId,null,null);
            if (doctorPageInfo==null || doctorPageInfo.isEmpty()){
                return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  ResultUtils.returnFail("出现异常,查看日志");
        }
        return ResultUtils.returnDataSuccess(doctorPageInfo.get(0));
    }

    @GetMapping("gettDepartmentsDoctor")
    @ApiOperation(value="获取同科室的医生",notes = "医生页面中，根据科室id,医院id和医生id获取同科室的医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tDepartmentsId",value = "科室id",required = true,dataType = "int"),
            @ApiImplicitParam(name = "hospitalId",value = "医院id",required = true,dataType = "int"),
            @ApiImplicitParam(name = "doctorId",value = "医生id",required = true,dataType = "int")
    })
    public Result gettDepartmentsDoctor(Integer tDepartmentsId, Integer hospitalId, Integer doctorId){
        List<DoctorDto> doctorDtos = null;
        List<DoctorDto> doctorDtos02 = new ArrayList<>();
        if (doctorId == null || tDepartmentsId == null || hospitalId == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        try {
            doctorDtos = doctorService.gettDepartmentsDoctor(tDepartmentsId, hospitalId, doctorId);
            if (doctorDtos == null || doctorDtos.size()<=0){
                //3005
                return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
            }
            if (doctorDtos.size()>4){
                for (int i = 0;i<=3;i++){
                    doctorDtos02.add(doctorDtos.get(i));
                }
                return ResultUtils.returnDataSuccess(doctorDtos02);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  ResultUtils.returnFail("出现异常,查看日志");
        }
        return ResultUtils.returnDataSuccess(doctorDtos);
    }

    @GetMapping("getDoctorByCondition")
    @ApiOperation(value="根据医生名字获取医生id",notes = "根据搜索框提供的医生姓名，和医院id查看医生的id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hospitalId",value = "医院id",required = true),
            @ApiImplicitParam(name = "doctorName",value = "医生姓名",required = true)
    })
    public Result getDoctorByCondition(@RequestParam(value = "doctorName",required = true)String doctorName,
                                       @RequestParam(value = "hospitalId",required = true)Integer hospitalId){
        int doctorId = 0;
        if (doctorName == null || doctorName == "" || hospitalId == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        try {
            List<Integer> list = doctorService.getDoctorByCondition(hospitalId, doctorName);
            if (list==null || list.size()<=0){
                return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
            }
            doctorId = list.get(0);
        } catch (Exception e) {
            e.printStackTrace();
            return  ResultUtils.returnFail("出现异常,查看日志");
        }
        return ResultUtils.returnDataSuccess(doctorId);
    }


    @GetMapping("/payDoctor")
    @ApiOperation(value="关注医生",notes = "关注医生，返回关注数")
    public Result payDoctor(Integer doctorId,HttpServletRequest request){
        Integer payNum = 1;

        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        User user = (User) redisUtil.get(token);


        Map<String,Object> map = new HashMap<>();
        map.put("doctorId",doctorId);
        map.put("userId",user.getId());

        List<PayDoctor> payDoctorListByMap = payDoctorService.getPayDoctorListByMap(map);
        if (payDoctorListByMap.size()>0){
            payNum = (Integer) redisUtil.get("payDoctor" + doctorId);
            Map<String,Object> map1 = new HashMap<>();
            map1.put("data",payNum);
            map1.put("msg","已关注过该医生");
            return ResultUtils.returnDataSuccess(map1);
        }
        PayDoctor payDoctor = new PayDoctor();
        payDoctor.setDoctorId(doctorId);
        payDoctor.setUserId(user.getId());
        payDoctor.setPayDoctorCreateTime(new Date());
        Integer integer = payDoctorService.qdtxAddPayDoctor(payDoctor);
        if (integer<=0){
            return ResultUtils.returnFail("关注失败，请退出登录重试");
        }
        payNum = (Integer) redisUtil.get("payDoctor" + doctorId);
        if (payNum == null){
            redisUtil.set("payDoctor"+doctorId,1);
            payNum = 1;
            return  ResultUtils.returnDataSuccess(payNum);
        }
        redisUtil.incr("payDoctor" + doctorId,1);
        return  ResultUtils.returnDataSuccess(payNum+1);
    }

    @GetMapping("unPayDoctor")
    @ApiOperation(value = "取消关注医生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId",value = "医生id")
    })
    public Result unPayDoctor(Integer doctorId,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        User user = (User) redisUtil.get(token);

        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("doctorId", doctorId);

        List<PayDoctor> payDoctorListByMap = payDoctorService.getPayDoctorListByMap(map);

        if (payDoctorListByMap == null || payDoctorListByMap.size() <= 0) {
            return ResultUtils.returnFail("数据出现错误，取消关注失败", ResultEnum.FAIL_HAVE_NOT_EXIST.getCode());
        }

        PayDoctor payDoctor = payDoctorListByMap.get(0);
        Integer payDoctorId = payDoctor.getPayDoctorId();
        Integer integer = payDoctorService.qdtxDeletePayDoctorById(payDoctorId);
        if (integer == null || integer <= 0) {
            return ResultUtils.returnFail("取消关注失败", ResultEnum.FAIL_HAVE_NOT_EXIST.getCode());

        }

        Integer payNum = (Integer) redisUtil.get("payDoctor" + payDoctorId);
        if (payNum != null && payNum > 0) {
            redisUtil.decr("payDoctor" + payDoctorId, 1);
        }
        return ResultUtils.returnSuccess();
    }

    @GetMapping("getPrices")
    @ApiOperation(value="根据医生id获取医生价钱",notes = "根据医生id获取医生价钱")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId",value = "医生id",required = true)
    })
    public Result getPrices(Integer doctorId){
        if(doctorId!=null){
            HashMap map = new HashMap();
            map.put("doctorId",doctorId);
            System.out.println("doctorId---------------------"+doctorId);
            ArrayList<Doctor> arrayList  = (ArrayList) doctorService.getDoctorListByMap(map);

            if(arrayList.size()!=0){
                System.out.println(arrayList);
              DoctorRole role =   doctorRoleService.getDoctorRoleById(((Doctor)arrayList.get(0)).getRoleId());
                return ResultUtils.returnDataSuccess(role);
            }
            return  ResultUtils.returnFail("医生不能为空");
        }
        return ResultUtils.returnFail();
    }

}


